﻿using WorkFlowCore.EventBus.Implements.Kafka;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;

namespace WorkFlowCore.EventBus
{
    public static class EventBusService
    {

        public static IServiceCollection AddDefautEventBus(this IServiceCollection services,params Assembly[] assemblies) 
        {
            services.AddSingleton(typeof(IEventBus), typeof(DefaultEventBus));
            services.AddSingleton(typeof(DefaultEventBus));
            foreach (var assembly in assemblies)
            {
                DefaultEventBus.RegistSubscriptions(assembly);
            }
            services.AddSingleton<EventBusManager>();
            return services;
        }
        public static IServiceCollection AddKafkaEventBus(this IServiceCollection services, Action<KafkaEventConfig> options)
        {
            services.AddSingleton(typeof(IEventBus), typeof(KafkaEventBus));
            services.AddSingleton(typeof(KafkaEventBus));
            var config = new KafkaEventConfig();
            options?.Invoke(config);
            services.AddSingleton(provider => config);
            services.AddSingleton<EventBusManager>();
            return services;
        }
        public static IApplicationBuilder InitGlobalEventBus(this IApplicationBuilder app)
        {
            //注册普通事件，该事件订阅在单应用有效无法分布式
            EventBusManager.Init(app.ApplicationServices);

            //注册kafka作为分布式事件
            var kafkaEventBus = app.ApplicationServices.GetService<KafkaEventBus>();
            var config = app.ApplicationServices.GetService<KafkaEventConfig>();
            var  configuration = app.ApplicationServices.GetService<IConfiguration>();
            Console.WriteLine("servers:" + configuration["KafkaBootstrapServers"]);
            if (kafkaEventBus!=null&&config!=null && config.RegisterAssemblies != null)
                kafkaEventBus.RegistSubscriptions(config.RegisterAssemblies);

            return app;

        }
    }
}
